package com.bacel.nb.product.web.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.bacel.nb.product.core.domain.Syslog;
import com.bacel.nb.product.core.domain.Sysuser;
import com.bacel.nb.product.core.dto.ListGageModule;
import com.bacel.nb.product.core.service.ILogsService;
import com.bacel.nb.product.core.service.ISysmoduleService;
import com.bacel.nb.product.core.service.ISysuserService;
import com.bacel.nb.product.web.template.ViewModel.FreeMarkerView;
import com.bacel.nb.product.web.util.MD5ArithmeticUtils;
import com.bacel.nb.product.web.util.WebUtilify;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.sql.Timestamp;
import java.util.HashMap;
import java.util.Map;

/**
 * Created by Bacel on 2017/4/6.
 */
@RestController
@RequestMapping(value = "/sysmanage/user", produces = "text/html;charset=UTF-8")
public class SysUserController {
    private final Logger logger = Logger.getLogger(SysUserController.class);

    @Autowired
    private ISysuserService sysuserService;
    @Autowired
    private ISysmoduleService sysmoduleService;
    @Autowired
    private ILogsService logsService;

    @RequestMapping(value = "/list", method = RequestMethod.GET)
    public final ModelAndView list(final HttpSession session, final HttpServletRequest request)
            throws Exception {
        String path = request.getContextPath();
        String menulist = WebUtilify.BuildMenuinfo(path, sysmoduleService);
        // 显示首页
        ModelAndView mav = new FreeMarkerView("user/list", "用户信息", path, menulist, session);
        return mav;
    }

    @RequestMapping(value = "/add", method = RequestMethod.GET)
    public final ModelAndView add(final HttpSession session, final HttpServletRequest request)
            throws Exception {
        String ports = String.valueOf(request.getServerPort());
        if (!ports.equals("80")) {
            ports = ":" + ports;
        }
        String basePath = request.getScheme() + "://" + request.getServerName() + ports;
        // 显示首页
        ModelAndView mav = new FreeMarkerView("user/add", "用户信息编辑", "", basePath + "/sysmanage/user/list", session);
        return mav;
    }

    @RequestMapping(value = "/edit", method = RequestMethod.POST, produces = "application/json;charset=UTF-8")
    public String edit(@RequestBody Sysuser module, final HttpServletRequest request) {
        String ret = "";
        String errstr = "";
        try {
            String password_old = request.getParameter("password_old");
            if (module != null && module.getName() != null) {
                if (module.getCreatedate() == null)
                    module.setCreatedate(new Timestamp(System.currentTimeMillis()));
                if (!module.getPassword().equals("") && !module.getPassword().equals(password_old)) {
                    module.setPassword(MD5ArithmeticUtils.getMd5(module.getPassword()));
                } else {
                    module.setPassword(password_old);
                }

                Sysuser olduser = CheckUser(module.getName(), module.getId());
                if (olduser != null && olduser.getId() > 0) {
                    errstr = "帐号已存在";
                }

                if (errstr.equals("")) {
                    if (module.getId() !=null) {
                        this.sysuserService.updateT(module);
                    } else {
                        this.sysuserService.insertT(module);
                    }
                    Syslog log = new Syslog();
                    log.setTitle("用户信息");
                    //TODO 需要等模块分好后来修改
                    log.setContent(JSON.toJSONString(module));
                    log.setCreatedate(new Timestamp(System.currentTimeMillis()));
                    WebUtilify.WriteLog(log, logsService);
                }
            }
            //this.channelService.updateChannel(dto);
        } catch (Exception ex) {
            ex.printStackTrace();
            errstr = "操作失败001";
        }
        ret = WebUtilify.ReturnJsoninfo(errstr);
        return ret;
    }

    @RequestMapping(value = "/listdata", method = RequestMethod.GET)
    public String listdata(final HttpServletRequest request)
            throws Exception {

        int pagesize = WebUtilify.parseInt(request.getParameter("rows"), 15);
        int pageindex = WebUtilify.parseInt(request.getParameter("page"), 1);
        String name = request.getParameter("name");
        ListGageModule datamodule = new ListGageModule<>();
        datamodule.setPagesize(pagesize);
        datamodule.setPageindex(pageindex);
        Sysuser sysuser = new Sysuser();
        sysuser.setName(name);
        sysuserService.getPageByExampleLike(sysuser, datamodule);
        Map<String, Object> info = new HashMap<>();
        info.put("records", datamodule.getTotalcount());
        info.put("total", datamodule.getPagecount());
        info.put("rows", datamodule.getList());
        String ret = "";
        try {
            ret = JSON.toJSONString(info);// JSONArray.toJSONString(datamodule);
        } catch (Exception ex) {
            System.out.println("moduledata:" + ex.toString());
            //logger.error("获取渠道列表错误:" + ex.toString());
            //logger.log .(ex,"channelList","获取渠道列表错误","");
        }
        return ret;
    }

    @RequestMapping(value = "/del", method = RequestMethod.POST)
    public String del(final HttpServletRequest request) {
        String ret = "";
        String errstr = "";
        try {
            Integer delid = Integer.parseInt(request.getParameter("id"));
            if (delid > 0)
                this.sysuserService.deleteByIdT(delid);
            else {
                errstr = "传递参数有误";
            }
            Syslog log = new Syslog();
            log.setTitle("用户信息");
            log.setContent(delid.toString());
            log.setCreatedate(new Timestamp(System.currentTimeMillis()));
            WebUtilify.WriteLog(log, logsService);
            //this.channelService.updateChannel(dto);
        } catch (Exception ex) {
            //logger.error(ex,"editChannel","更新渠道错误","");
        }
        ret = WebUtilify.ReturnJsoninfo(errstr);
        return ret;
    }

    @RequestMapping(value = "/getmodule", method = RequestMethod.GET)
    public String getmodule(final HttpServletRequest request)
            throws Exception {
        Integer id = Integer.parseInt(request.getParameter("id"));
        Sysuser module = this.sysuserService.get(id);
        if (module != null)
            return JSON.toJSONString(module);
        return "";
    }

    private Sysuser CheckUser(String code, Integer userid) {
        if (userid == null){
            return null;
        }
        Sysuser module = sysuserService.get(userid);
        if (module==null||module.getId()<=0||module.getName().equals(code)){
            return null;
        }
        return module;
    }
}
